package com.woniuxy.patrol.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.common.utils.ResponseUtil;
import com.woniuxy.patrol.mapper.PatrolPlanRouteMapper;
import com.woniuxy.patrol.mapper.PatrolPointMapper;
import com.woniuxy.patrol.mapper.PatrolRoutePointMapper;
import com.woniuxy.patrol.pojo.PatrolPlanRoute;
import com.woniuxy.patrol.pojo.PatrolPoint;
import com.woniuxy.patrol.pojo.PatrolRoute;
import com.woniuxy.patrol.pojo.PatrolRoutePoint;
import com.woniuxy.patrol.service.PatrolRouteService;
import com.woniuxy.patrol.mapper.PatrolRouteMapper;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.Collections;
import java.util.*;

/**
* @author 13162
* @description 针对表【wcm_patrol_route(巡更路线表)】的数据库操作Service实现
* @createDate 2025-07-14 19:22:37
*/
@Service
public class PatrolRouteServiceImpl extends ServiceImpl<PatrolRouteMapper, PatrolRoute>
    implements PatrolRouteService{


    @Resource
    private PatrolRouteMapper routeMapper;
    @Resource
    private PatrolRoutePointMapper routePointMapper;
    @Resource
    private PatrolPointMapper patrolPointMapper;
    @Resource
    private PatrolPlanRouteMapper planRouteMapper; // 新增：计划-路线关联Mapper
    @Override
    public ResponseUtil getByCommunityId(Long communityId) {
        // 对应《巡更demo.docx》中按社区筛选路线的功能
        List<PatrolRoute> routes = routeMapper.selectByCommunityId(communityId);
        return ResponseUtil.success(routes);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseUtil addRoute(PatrolRoute route, List<Long> pointIds) {
        // 1. 保存路线基本信息
        route.setStatus(1); // 默认为启用
        route.setIsDelete(1);
        route.setCreateTime(new Date());
        route.setUpdateTime(new Date());
        save(route);

        // 2. 保存路线-点位关联（对应《巡更demo.docx》中选择巡更点并排序的功能）
        if (pointIds != null && !pointIds.isEmpty()) {
            List<PatrolRoutePoint> relationList = new ArrayList<>();
            for (int i = 0; i < pointIds.size(); i++) {
                PatrolRoutePoint relation = new PatrolRoutePoint();
                relation.setRouteId(route.getRouteId());
                relation.setPointId(pointIds.get(i));
                relation.setSeqNo(i + 1); // 排序号
                relation.setIsDelete(1);
                relation.setCreateTime(new Date());
                relation.setUpdateTime(new Date());
                relationList.add(relation);
            }
            routePointMapper.batchInsert(relationList);
        }

        return ResponseUtil.success("巡更路线添加成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseUtil updateRoute(PatrolRoute route, List<Long> pointIds) {
        // 1. 更新路线信息
        route.setUpdateTime(new Date());
        updateById(route);

        // 2. 先删除原有关联，再添加新关联（对应《巡更demo.docx》中编辑路线时重新选择点位）
        routePointMapper.deleteByRouteId(route.getRouteId());
        if (pointIds != null && !pointIds.isEmpty()) {
            List<PatrolRoutePoint> relationList = new ArrayList<>();
            for (int i = 0; i < pointIds.size(); i++) {
                PatrolRoutePoint relation = new PatrolRoutePoint();
                relation.setRouteId(route.getRouteId());
                relation.setPointId(pointIds.get(i));
                relation.setSeqNo(i + 1);
                relation.setIsDelete(1);
                relation.setCreateTime(new Date());
                relation.setUpdateTime(new Date());
                relationList.add(relation);
            }
            routePointMapper.batchInsert(relationList);
        }

        return ResponseUtil.success("巡更路线更新成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseUtil deleteRoute(Long routeId) {
        // 1. 删除路线
        PatrolRoute route = new PatrolRoute();
        route.setRouteId(routeId);
        route.setIsDelete(0);
        route.setUpdateTime(new Date());
        updateById(route);

        // 2. 删除关联关系
        routePointMapper.deleteByRouteId(routeId);
        // 3. 删除路线-计划关联（新增：通过wcm_patrol_plan_route表）
        planRouteMapper.delete(new QueryWrapper<PatrolPlanRoute>()
                .eq("route_id", routeId)
                .eq("is_delete", 1));

        return ResponseUtil.success("巡更路线删除成功");
    }
    @Override
    public ResponseUtil getRouteDetail(Long routeId) {
        // 1. 查询路线基本信息
        PatrolRoute route = getById(routeId);
        if (route == null || route.getIsDelete() == 0) {
            return ResponseUtil.error("路线不存在");
        }

        // 2. 查询路线关联的点位（通过wcm_patrol_route_point表）
        List<PatrolPoint> points = patrolPointMapper.selectByRouteId(routeId);

        // 3. 查询路线关联的计划（新增：通过wcm_patrol_plan_route表）
        List<Long> planIds = planRouteMapper.selectPlanIdsByRouteId(routeId);

        // 4. 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("route", route);
        result.put("points", points);
        result.put("pointCount", points.size());
        result.put("planIds", planIds); // 新增：关联的计划ID列表

        return ResponseUtil.success(result);
    }

    // 新增方法：根据计划ID获取路线列表
    @Override
    public ResponseUtil getByPlanId(Long planId) {
        List<PatrolRoute> routes = routeMapper.selectByPlanId(planId);
        return ResponseUtil.success(routes);
    }

    /**
     * 导出Excel实现
     */
    @Override
    public ByteArrayOutputStream exportRecords(Long communityId) {
        // 1. 查询需要导出的数据（按社区筛选，只查未删除的路线）
        QueryWrapper<PatrolRoute> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("community_id", communityId)
                .eq("is_delete", 1) // 只导出未删除的记录
                .orderByDesc("create_time");
        List<PatrolRoute> routes = routeMapper.selectList(queryWrapper);

        // 2. 预查询所有路线关联的点位（减少SQL查询次数）
        Map<Long, List<PatrolPoint>> routePointsMap = getRoutePointsMap(routes);

        // 3. 创建Excel并写入数据
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("巡更路线记录");

        // 3.1 创建表头
        XSSFRow headerRow = sheet.createRow(0);
        String[] headers = {"序号", "路线名称", "所属社区", "状态", "点位数量", "包含点位", "创建时间", "描述"};
        for (int i = 0; i < headers.length; i++) {
            headerRow.createCell(i).setCellValue(headers[i]);
        }

        // 3.2 写入数据行
        for (int i = 0; i < routes.size(); i++) {
            PatrolRoute route = routes.get(i);
            XSSFRow dataRow = sheet.createRow(i + 1);

            // 序号
            dataRow.createCell(0).setCellValue(i + 1);
            // 路线名称
            dataRow.createCell(1).setCellValue(route.getRouteName());
            // 所属社区（假设communityId对应名称需要额外查询，这里简化处理）
            dataRow.createCell(2).setCellValue("社区ID:" + route.getCommunityId());
            // 状态
            dataRow.createCell(3).setCellValue(route.getStatus() == 1 ? "启用" : "禁用");
            // 点位数量
            List<PatrolPoint> points = routePointsMap.getOrDefault(route.getRouteId(), Collections.emptyList());
            dataRow.createCell(4).setCellValue(points.size());
            // 包含点位（取前3个点位名称）
            String pointNames = points.stream()
                    .map(PatrolPoint::getPointName)
                    .limit(3)
                    .collect(Collectors.joining(","));
            if (points.size() > 3) {
                pointNames += "...";
            }
            dataRow.createCell(5).setCellValue(pointNames);
            // 创建时间
            dataRow.createCell(6).setCellValue(route.getCreateTime().toString());
            // 描述
            dataRow.createCell(7).setCellValue(route.getRemark() != null ? route.getRemark() : "");
        }

        // 4. 调整列宽（可选）
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }

        // 5. 将Excel写入字节流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            workbook.write(outputStream);
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException("导出Excel失败", e);
        }
        return outputStream;
    }

    /**
     * 批量查询路线关联的点位，返回Map<routeId, List<PatrolPoint>>
     */
    private Map<Long, List<PatrolPoint>> getRoutePointsMap(List<PatrolRoute> routes) {
        // 提取所有路线ID
        List<Long> routeIds = routes.stream()
                .map(PatrolRoute::getRouteId)
                .collect(Collectors.toList());

        if (routeIds.isEmpty()) {
            return Collections.emptyMap();
        }

        // 查询所有关联的点位ID
        QueryWrapper<PatrolRoutePoint> rpQuery = new QueryWrapper<>();
        rpQuery.in("route_id", routeIds)
                .eq("is_delete", 1)
                .orderByAsc("seq_no"); // 按排序号升序
        List<PatrolRoutePoint> routePoints = routePointMapper.selectList(rpQuery);

        // 提取所有点位ID
        List<Long> pointIds = routePoints.stream()
                .map(PatrolRoutePoint::getPointId)
                .collect(Collectors.toList());

        // 查询点位详情
        List<PatrolPoint> points = patrolPointMapper.selectBatchIds(pointIds);
        Map<Long, PatrolPoint> pointMap = points.stream()
                .collect(Collectors.toMap(PatrolPoint::getPointId, p -> p));

        // 组装路线-点位映射
        return routePoints.stream()
                .collect(Collectors.groupingBy(
                        PatrolRoutePoint::getRouteId,
                        Collectors.mapping(
                                rp -> pointMap.get(rp.getPointId()),
                                Collectors.toList()
                        )
                ));
    }


}




